package com.modai.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ：modai
 * @date ：Created in 2020-12-6 16:43
 * @description：
 */
@Component
public class MyLB implements ILoadBalancer {


    private AtomicInteger atomicInteger = new AtomicInteger(0);

    private final int getAndIncrease(int size) {
        for (; ; ) {
            int current = atomicInteger.get();
            int next = (current+1)%size;
            if (atomicInteger.compareAndSet(current, next)) {
                System.out.println("**********下一个是："+next);
                return next;
            }
        }
    }

    @Override
    public ServiceInstance getServiceInstances(List<ServiceInstance> serviceInstanceList) {
        int serviceInstanceSize = serviceInstanceList.size();

        return serviceInstanceList.get(getAndIncrease(serviceInstanceSize));
    }
}
